<template>
  <div ref="chartRef" style="width: 100%; height: 400px;"></div>
</template>

<script setup lang="ts">
import { ref, onMounted, onBeforeUnmount, watch } from 'vue'
import * as echarts from 'echarts'

const props = defineProps({
  option: {
    type: Object,
    required: true
  }
})

const chartRef = ref<HTMLElement>()
let chartInstance: echarts.ECharts | null = null

// 初始化图表
const initChart = () => {
  if (chartRef.value) {
    chartInstance = echarts.init(chartRef.value)
    chartInstance.setOption(props.option)

    // 窗口大小变化时重新调整图表大小
    window.addEventListener('resize', resizeChart)
  }
}

// 调整图表大小
const resizeChart = () => {
  chartInstance?.resize()
}

// 组件挂载时初始化
onMounted(initChart)

// 选项变化时更新图表
watch(() => props.option, (newOption) => {
  chartInstance?.setOption(newOption)
}, { deep: true })

// 组件卸载前销毁图表
onBeforeUnmount(() => {
  window.removeEventListener('resize', resizeChart)
  chartInstance?.dispose()
})
</script>